<?php

namespace App\Exports;

use App\Models\Download;
use App\Models\EntityApplyRecord;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class EntityApplyExport implements FromQuery, WithMapping, WithHeadings
{
    public $data;
    public $request;

    public function __construct(Download $data)
    {
        $this->data = $data;
        $this->request = json_decode($this->data->request, true);
    }

    public function query() // 返回的数据
    {
        return EntityApplyRecord::query()->where('agent_id', $this->data->agent_id)
            ->when(request()->keyword, function ($q) {
                $likeVal = '%' . request()->keyword . '%';
                $q->whereHas('user', function ($q1) use ($likeVal) {
                    return $q1->where('mobile', 'like', $likeVal)->orWhere('nickname', 'like', $likeVal);
                });
            })
            ->when(request()->status, function ($q) {
                return $q->where('status', request()->status);
            })
            ->when(request()->start_date, function ($q) {
                return $q->where('created_at', '>=', request()->start_date);
            })
            ->when(request()->end_date, function ($q) {
                return $q->where('created_at', '<=', request()->end_date);
            })
            ->with(['user', 'entity', 'product'])
            ->orderByDesc('id');
    }

    public function map($value): array // 指定excel中每一列的数据字段
    {
        return [
            $value['id'],
            $value['entity']->name,
            $value['product']->name,
            $value['created_at'],
            $value['exchange_count'],
            $value['user']->nickname,
            $value['user']->mobile,
            $value['address'],
            $value['express_name'],
            $value['logistics_no'],
        ];
    }

    public function headings(): array // 指定excel的表头
    {
        return [
            'ID',
            '实物名称',
            '绑定资产',
            '申请时间',
            '兑换数量',
            '姓名',
            '手机号',
            '收货地址',
            '快递名称',
            '物流单号',
        ];
    }
}
